import Vue from "vue";

Vue.filter("filterDate", (value, fmt) => {
  if (!value) return "";

  const date = new Date(value);
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+":
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1,
    "d+": date.getDate() < 10 ? "0" + date.getDate() : date.getDate(),
    "h+": date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
    "m+": date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
    "s+": date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : str);
    }
  }
  return fmt;
});

Vue.filter("getWeek", value => {
  if (!value) return "-";
  const date = new Date(value);
  const num = date.getDay();
  let week = "星期";
  switch (num) {
    case 0:
      week += "日";
      break;
    case 1:
      week += "一";
      break;
    case 2:
      week += "二";
      break;
    case 3:
      week += "三";
      break;
    case 4:
      week += "四";
      break;
    case 5:
      week += "五";
      break;
    case 6:
      week += "六";
      break;
    default:
      break;
  }
  return week;
});

Vue.filter("costTime", value => {
  if (!value) return "-";
  const time = Math.floor(value / 1000);
  const day = Math.floor(time / (3600 * 24));
  const hour = Math.floor((time - day * 3600 * 24) / 3600);
  const minute = Math.floor((time - day * 3600 * 24 - hour * 3600) / 60);
  const second = Math.floor(time - day * 3600 * 24 - hour * 3600 - minute * 60);
  let str = "";
  if (day > 0) {
    str += day + "天";
  }
  if (hour > 0) {
    str += hour + "时";
  }
  if (minute > 0) {
    str += minute + "分";
  }
  str += second + "秒";
  return str;
});

// 字符串截取
Vue.filter("ellipsis", (value, num) => {
  if (!value) return "";
  if (value.length > num) {
    return value.slice(0, num) + "...";
  }
  return value;
});

// 分割分数
Vue.filter("cutGrade", (value, num) => {
  if (value) {
    return value.split("/")[num];
  }
  return "";
});

// 保留两位小数
Vue.filter("number", value => {
  if (value) {
    return value.toFixed(2);
  }
  return 0.0;
});

/**
 * 截取字符串 中英文混合
 * @param str	待处理字符串
 * @param len	截取字节长度 中文2字节 英文1字节
 */
Vue.filter("cutSubstr", (str, len)=>{
  var regexp = /[^\x00-\xff]/g; // 正在表达式匹配中文
	// 当字符串字节长度小于指定的字节长度时
	if (str.replace(regexp, "aa").length <= len) {
		return str;
	}
	// 假设指定长度内都是中文
	var m = Math.floor(len/2);
	for (var i = m, j = str.length; i < j; i++) {
		// 当截取字符串字节长度满足指定的字节长度
		if (str.substring(0, i).replace(regexp, "aa").length >= len) {
			return str.substring(0, i) + "...";
		}
	}
	return str;
});


// 指定字符串替换空
Vue.filter("strEmpty", value => {
  if (value) {
    return value.replace(/T|Z/g, '');
  }
});
